﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Northwind.Repositories;
using Northwind.Repositories.Entity;
using jQuery.InfiniteScroll.Models;
using Lib.Web.Mvc;

namespace jQuery.InfiniteScroll.Controllers
{
    public class HomeController : Controller
    {
        #region Fields
        IProductsRepository _productsRepository;
        #endregion

        #region Constructors
        public HomeController()
            : this(new ProductsRepository())
        {
        }

        public HomeController(IProductsRepository productsRepository)
        {
            _productsRepository = productsRepository;
        }
        #endregion

        #region Actions
        [NoAjaxRequest]
        public ViewResult Products(int? page)
        {
            return View(GetProductsViewModel(page));
        }

        [AjaxRequest]
        [ActionName("Products")]
        public PartialViewResult ProductsList(int? page)
        {
            return PartialView("ProductsList", GetProductsViewModel(page));
        }
        #endregion

        #region Methods
        private ProductsViewModel GetProductsViewModel(int? page)
        {
            ProductsViewModel viewModel = new ProductsViewModel()
            {
                CurrentPageIndex = page.HasValue ? page.Value : 1,
                PageRecordsCount = 10,
                TotalRecordsCount = _productsRepository.GetCount(String.Empty)
            };
            viewModel.Products = _productsRepository.FindRange(String.Empty, "Name", (viewModel.CurrentPageIndex - 1) * viewModel.PageRecordsCount, viewModel.PageRecordsCount);

            return viewModel;
        }
        #endregion
    }
}
